package com.yangjun.service.report;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yangjun.common.DVConstants;
import com.yangjun.common.ServerResponse;
import com.yangjun.common.comparator.TargetItemComparator;
import com.yangjun.common.comparator.TargetItemComparatorByTargetArr;
import com.yangjun.common.excel.DataBaseExcelContext;
import com.yangjun.common.excel.ExcelExportResult;
import com.yangjun.dao.mybatis.mapper.report.ActivePackageReportExportMapper;
import com.yangjun.dao.mybatis.mapper.report.DvReportSearchTmpMapper;
import com.yangjun.dao.mybatis.mapper.report.ReportDownloadStatusMapper;
import com.yangjun.dao.mybatis.mapper.report.ReportExportStatusMapper;
import com.yangjun.dao.mybatis.mapper.report.ReportImportStatusMapper;
import com.yangjun.entity.report.DvExcelFieldDefinitionEntity;
import com.yangjun.entity.report.DvReportDownloadStatusEntity;
import com.yangjun.entity.report.DvReportExportStatus;
import com.yangjun.entity.report.DwActivePackageEntity;
import com.yangjun.po.report.ActivePackageReportExportPO;
import com.yangjun.service.common.CommonService;
import com.yangjun.service.permission.ReportExportPermissionService;
import com.yangjun.utils.DvDateUtils;
import com.yangjun.utils.DvUtils;
import com.yangjun.utils.POIExcelUtils;
import com.yangjun.vo.report.AcitvePackageReportManageVO;
import com.yangjun.vo.report.ActivePackageReportExportVO;

@Service
public class ActivePackageReprotExportService {
	@Value("${excel.uploadPath}")
    private String uploadPath;
	@Value("${excel.downloadPath}")
    private String downloadPath;
	@Autowired
	private DataBaseExcelContext context;
	
	private final static String reporttype = "activePackage";
	@Autowired
	private ActivePackageReportExportMapper activePackageReportExportMapper;
	@Autowired
	private ReportExportStatusMapper reportExportStatusMapper;
	@Autowired
	private ReportImportStatusMapper reportImportStatusMapper;
	@Autowired
	private DvReportSearchTmpMapper dvReportSearchTmpMapper;
	@Autowired
	private ReportCommonService reportCommonService;
	@Autowired
	private CommonService commonService;
	@Autowired
	private ReportExportPermissionService reportExportPermissionService;
	@Autowired
	private ReportDownloadStatusMapper reportDownloadStatusMapper;
	
	/**
	 * @Description 获取维度信息
	 * @return
	 * @author yangjun
	 * @Date 2017年7月5日 上午11:50:06
	 */
	public Object getDeminsion(String reportid,String userid){
		ActivePackageReportExportVO apreVo = null;
		DvReportExportStatus dvReportExportStatus = reportExportStatusMapper.queryReportStatusByReportId(reportid);
		
		String[] targetSelectData  = null;
		//修改报表排序号的字段顺序
		List<Map<String,Object>> sortTargetSelectData=Lists.newArrayList();
		String reportName = "营销活动-";
		String uploadFileId = "";
		String uploadFileName = "";
		String searchName = "activeCode";
		//平台
		List<Map<String, Object>> ordersource = Lists.newArrayList();
		String[] saveOrdersourceArr=null;
		//活动类型
		String[] activeTypeArr = null;
		//是否全场
		String[] isWhole = null;
		//是否停用
		String[] isStopUse = null;
		//是否审核
		String[] isVerify = null;
		//是否模板显示
		String[] isTempletShow = null;
		//是否标签显示
		String[] isLabelShow = null;
		
		String startBeginDate = "";//活动开始时间范围的开始时间 
		String startEndDate = "";//活动开始时间范围的结束时间 
		String finishBeginDate = "";//活动结束时间范围的开始时间 
		String finishEndDate = "";//活动结束时间范围的结束时间 
		String onlineDate = "";//活动在线时间
		
		if(dvReportExportStatus!=null){
			//订阅报表没有末次下单选项
			apreVo = JSON.parseObject(dvReportExportStatus.getReportparam(), ActivePackageReportExportVO.class);
			saveOrdersourceArr = apreVo.getOrdersource();
			activeTypeArr = apreVo.getActiveType();
			
			isWhole = apreVo.getIsWhole();
			isStopUse = apreVo.getIsStopUse();
			isVerify = apreVo.getIsVerify();
			isTempletShow = apreVo.getIsTempletShow();
			isLabelShow = apreVo.getIsLabelShow();
			
			startBeginDate = apreVo.getStartBeginDate();
			startEndDate = apreVo.getStartEndDate();
			finishBeginDate = apreVo.getFinishBeginDate();
			finishEndDate = apreVo.getFinishEndDate();
			onlineDate = apreVo.getOnlineDate();
			
			targetSelectData = apreVo.getTarget();
			reportName = apreVo.getReportName();
			uploadFileId = apreVo.getUploadFileId();
			if(StringUtils.isNotBlank(uploadFileId)){
				uploadFileName = reportImportStatusMapper.queryReportStatusByUUID(uploadFileId).getReportName();
			}
			searchName = apreVo.getSearchName();
		}
		Map<String,Object> demensionMap = Maps.newLinkedHashMap();
		List<DvExcelFieldDefinitionEntity> excelFieldDefinitionList = reportCommonService.getExcelFieldDefinitionList(reporttype);
		//获取每个报表的指标分类
		Map<String,String> tmpCategoryMap = reportCommonService.queryCategory(reporttype);
		List<Map<String,String>> categoryList = Lists.newArrayList();
		
		Map<String,List<Map<String,Object>>> targetMap = Maps.newHashMap();
		List<Map<String,Object>> targetList =null;
		for(Map.Entry<String,String> categoryEntry: tmpCategoryMap.entrySet()){
			//初始化指标分类数组
			Map<String,String> categoryMap = Maps.newHashMap();
			categoryMap.put("name", categoryEntry.getKey());
			categoryMap.put("value", categoryEntry.getValue());
			categoryList.add(categoryMap);
			//初始化指标分类内容
			targetList = Lists.newArrayList();
			targetMap.put(categoryEntry.getKey(),targetList);
		}
		//查询有权限显示的报表字段
		String[] allowFieldArr = reportExportPermissionService.getReportAllowField(userid, reporttype);
		if(allowFieldArr!=null&&allowFieldArr.length>0){
			for(DvExcelFieldDefinitionEntity excelFieldDefinitionEntity : excelFieldDefinitionList){
				//权限控制能够显示的字段，如果查询不到对应角色的权限直接不显示字段。
				if(allowFieldArr!=null){
					List<String> allowFieldList = Arrays.asList(allowFieldArr);
					if(!allowFieldList.contains(excelFieldDefinitionEntity.getEntityName())){
						continue;
					}
				}
				//封装默认的指标格式
				String categoryId = excelFieldDefinitionEntity.getCategoryId();
				if(StringUtils.isNotBlank(categoryId)){
					String entityName = excelFieldDefinitionEntity.getEntityName();
					String title = excelFieldDefinitionEntity.getTitle();
					int sort = excelFieldDefinitionEntity.getFieldSort();
					Map<String,Object> itemMap = Maps.newHashMap();
					itemMap.put("value", entityName);
					itemMap.put("name", title);
					itemMap.put("sort", sort);
					itemMap.put("checked", false);
					if(targetSelectData!=null){
						for(int i=0,len=targetSelectData.length;i<len;i++){
							if(entityName.equals(targetSelectData[i])){
								itemMap.put("checked", true);
								//修改报表排序号的字段顺序
								sortTargetSelectData.add(itemMap);
							}
						}
					}
					targetList = targetMap.get(categoryId);
					targetList.add(itemMap);
				}
			}
			for(Map.Entry<String,List<Map<String,Object>>> targetItemEntry : targetMap.entrySet()){
				Collections.sort(targetItemEntry.getValue(),new TargetItemComparator());
			}
		}
		demensionMap.put("isWhole", reportCommonService.HandleCheackBoxStatus(Arrays.asList(DVConstants.REPORT_TRUE_FALSE),isWhole));
		demensionMap.put("isStopUse", reportCommonService.HandleCheackBoxStatus(Arrays.asList(DVConstants.REPORT_TRUE_FALSE),isStopUse));
		demensionMap.put("isVerify", reportCommonService.HandleCheackBoxStatus(Arrays.asList(DVConstants.REPORT_TRUE_FALSE),isVerify));
		demensionMap.put("isTempletShow", reportCommonService.HandleCheackBoxStatus(Arrays.asList(DVConstants.REPORT_TRUE_FALSE),isTempletShow));
		demensionMap.put("isLabelShow", reportCommonService.HandleCheackBoxStatus(Arrays.asList(DVConstants.REPORT_TRUE_FALSE),isLabelShow));
		demensionMap.put("activeType", reportCommonService.HandleCheackBoxStatus(commonService.getActiveType(),activeTypeArr));

		//平台
		List<String> platformList = reportExportPermissionService.getUserExcelDimSet(userid, reporttype);
		ordersource = commonService.getPlatformList();
		if(ordersource!=null){
		    Iterator<Map<String, Object>> it = ordersource.iterator();    
		    while(it.hasNext()){  
				Map<String, Object> ordersourceItem = (Map<String, Object>) it.next();
				String sourcename = ordersourceItem.get("sourcename").toString();
				if(platformList!=null&&!platformList.contains(sourcename)){
					it.remove();
				}
		    }
		}
		//平台
				for(Map<String, Object> ordersourceItem : ordersource){
					if(saveOrdersourceArr!=null){
						ordersourceItem.put("checked", false);
						String[] os = ordersourceItem.get("ordersource").toString().split(",");
						for(String osItem : os){
							if(ArrayUtils.contains(saveOrdersourceArr, osItem)){
								ordersourceItem.put("checked", true);
							}
						}
					}else{
						ordersourceItem.put("checked", true);
					}
				}
		demensionMap.put("ordersource",ordersource);
		demensionMap.put("startBeginDate",startBeginDate);
		demensionMap.put("startEndDate",startEndDate);
		demensionMap.put("finishBeginDate",finishBeginDate);
		demensionMap.put("finishEndDate",finishEndDate);
		demensionMap.put("onlineDate",onlineDate);

		
		String[] searchWayNameArr = {"活动编码","活动名称"};
		String[] searchWayValueArr = {"activeCode","activeName"};
		List<Map<String,String>> searchWayList = Lists.newArrayList();
		for(int i = 0,len=searchWayNameArr.length;i<len;i++){
			Map<String,String> searchMap = Maps.newHashMap();
			searchMap.put("searchWayName", searchWayNameArr[i]);
			searchMap.put("searchWayValue", searchWayValueArr[i]);
			searchWayList.add(searchMap);
		}
		demensionMap.put("search", searchWayList);
		demensionMap.put("searchName", searchName);
		
		
		
		demensionMap.put("category", categoryList);//分类
		demensionMap.put("uploadFileName", uploadFileName);
		demensionMap.put("uploadFileId", uploadFileId);
		demensionMap.put("reportName",reportName);
		demensionMap.put("reporttype", reporttype);
		demensionMap.put("target", targetMap);
		demensionMap.put("update", "每天整点");
		Collections.sort(sortTargetSelectData, new TargetItemComparatorByTargetArr(targetSelectData));
		demensionMap.put("sortTarget", sortTargetSelectData);
		
		reportCommonService.deleteUploadReport(userid);
		return ServerResponse.createBySuccess(demensionMap);
	}

	public Object queryData(String reportid){
		DvReportExportStatus dvReportExportStatus = reportExportStatusMapper.queryReportStatusByReportId(reportid);
		ActivePackageReportExportVO apreVo = JSON.parseObject(dvReportExportStatus.getReportparam(), ActivePackageReportExportVO.class);
		return queryData(apreVo);
	}
	
	public Object queryData(ActivePackageReportExportVO apreVo){
		ActivePackageReportExportPO activePackageReportExportPO = new ActivePackageReportExportPO();
		if(apreVo.getOrdersource()==null||apreVo.getOrdersource().length<1){
			return ServerResponse.createByErrorMessage("平台为空,请修改报表！");
		}
		Map<String,Object> resultMap = Maps.newHashMap();
		String[] targetArr = apreVo.getTarget();
		List<String> targetList = getTargetList(targetArr) ;
//		System.out.println(Arrays.toString(targetList.toArray(new String[targetList.size()])));
		handleTargetSql(activePackageReportExportPO,targetList);
		Long start = System.currentTimeMillis();
		List<DvExcelFieldDefinitionEntity>  reportFieldDefinition= reportCommonService.getExcelFieldDefinitionList(reporttype);
		//装载表格数据
		List<List<String>> tableList = Lists.newArrayList();
		List<String> titleList = Lists.newArrayList();
		for(String item : targetList){
			for(DvExcelFieldDefinitionEntity definition : reportFieldDefinition){
				String name = definition.getEntityName();
				if(item.equals(name)){
					titleList.add(definition.getTitle());
					addCategory(activePackageReportExportPO,definition.getCategoryId());
				}
			}
		}
		tableList.add(titleList);
		System.out.println("1."+(System.currentTimeMillis()-start)/1000);
		
		List<String> searchItemList = Lists.newArrayList();
		//查找附件内容作为搜索条件
		if("activeCode".equals(apreVo.getSearchName())){
			if(StringUtils.isNotBlank(apreVo.getUploadFileId())){
				int partSize=1000;
				String fileName = reportImportStatusMapper.queryReportStatusByUUID(apreVo.getUploadFileId()).getFileName();
				File uploadFile = new File(uploadPath+fileName);
				FileInputStream readStream = null;
				try {
					readStream = new FileInputStream(uploadFile);
					List<List<Object>> datas =POIExcelUtils.readExcel(readStream, 0);
					for(int i=0,len=datas.size();i<len;i++){
						if(i>0&&datas.get(i).get(0)!=null){
							searchItemList.add(datas.get(i).get(0).toString());
						}
					}
					dvReportSearchTmpMapper.deleteDvReportSearchTmp(apreVo.getUserid());
					if(searchItemList.size()>partSize){
						int part = searchItemList.size()/partSize;
						for(int i=0;i<part;i++){
							List<String> tmpList  = searchItemList.subList(0, partSize);
							dvReportSearchTmpMapper.insertDvReportSearchTmpByBatch(apreVo.getUserid(), tmpList);
							searchItemList.subList(0, partSize).clear();
						}
					}
					if(searchItemList.size()>0){
						dvReportSearchTmpMapper.insertDvReportSearchTmpByBatch(apreVo.getUserid(), searchItemList);
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				apreVo.setSearchValue(searchItemList.size()>0?searchItemList.toArray(new String[searchItemList.size()]):null);
			}else{
				apreVo.setSearchValue(null);
			}
		}else if("activeName".equals(apreVo.getSearchName())){
			if(apreVo.getSearchValue().length>0){
				if(StringUtils.isNotBlank(apreVo.getSearchValue()[0])){
					apreVo.setSearchValue(apreVo.getSearchValue());
				}
			}else{
				apreVo.setSearchValue(null);
			}
		}
		System.out.println("2."+(System.currentTimeMillis()-start)/1000);
		BeanUtils.copyProperties(apreVo,activePackageReportExportPO);
		List<DwActivePackageEntity> list = activePackageReportExportMapper.queryData(activePackageReportExportPO,1,10);
		JSONArray objectArr = JSON.parseArray(JSONObject.toJSONString(list));
		for(int i = 0,len = objectArr.size() ; i<len ; i++){
			JSONObject object = objectArr.getJSONObject(i);
			List<String> itemList = Lists.newArrayList();
			for(String item : targetList){
				itemList.add(object.getString(item)==null?"":object.getString(item));
			}
			tableList.add(itemList);
		}
		System.out.println("3."+(System.currentTimeMillis()-start)/1000);
		resultMap.put("tableData",tableList );
		resultMap.put("rownum",list.size()>0?list.get(0).getCountNum():0);
		return ServerResponse.createBySuccess(resultMap);
	}
	
	
	public Object addDownloadTask(String reportid,HttpServletRequest request){
		DvReportExportStatus dvReportExportStatus = reportExportStatusMapper.queryReportStatusByReportId(reportid);
		ActivePackageReportExportVO apreVo = JSON.parseObject(dvReportExportStatus.getReportparam(), ActivePackageReportExportVO.class);
		return download(apreVo,request);
	}
	
	public Object addDownloadTask(ActivePackageReportExportVO apreVo,HttpServletRequest request){
		if(reportDownloadStatusMapper.queryReportByName(apreVo.getUserid(), apreVo.getReportName())>0){
			return ServerResponse.createByErrorMessage("已存在相同名称的报表，请重新命名!");
		}else{
			return download(apreVo,request);
		}
	}
	
	public Object download(ActivePackageReportExportVO apreVo,HttpServletRequest request){
		context.initDBExcelDefinitionReader("export");
		List<DvExcelFieldDefinitionEntity>  reportFieldDefinition= reportCommonService.getExcelFieldDefinitionList(reporttype);
		ActivePackageReportExportPO aprePo= new ActivePackageReportExportPO();
		String[] targetArr = apreVo.getTarget();
		List<String> targetList = getTargetList(targetArr) ;
		handleTargetSql(aprePo,targetList);
		for(String item : targetList){
			for(DvExcelFieldDefinitionEntity definition : reportFieldDefinition){
				String name = definition.getEntityName();
				if(item.equals(name)){
					//添加分类
					addCategory(aprePo,definition.getCategoryId());
				}
			}
		}
		//mybatis无法判断数组长度
		List<String> searchItemList = Lists.newArrayList();
		//查找附件内容作为搜索条件
			if("activeCode".equals(apreVo.getSearchName())){
				if(StringUtils.isNotBlank(apreVo.getUploadFileId())){
					int partSize=1000;
					String fileName = reportImportStatusMapper.queryReportStatusByUUID(apreVo.getUploadFileId()).getFileName();
					File uploadFile = new File(uploadPath+fileName);
					FileInputStream readStream = null;
					try {
						readStream = new FileInputStream(uploadFile);
						List<List<Object>> datas =POIExcelUtils.readExcel(readStream, 0);
						for(int i=0,len=datas.size();i<len;i++){
							if(i>0&&datas.get(i).get(0)!=null){
								searchItemList.add(datas.get(i).get(0).toString());
							}
						}
						dvReportSearchTmpMapper.deleteDvReportSearchTmp(apreVo.getUserid());
						if(searchItemList.size()>partSize){
							int part = searchItemList.size()/partSize;
							for(int i=0;i<part;i++){
								List<String> tmpList  = searchItemList.subList(0, partSize);
								dvReportSearchTmpMapper.insertDvReportSearchTmpByBatch(apreVo.getUserid(), tmpList);
								searchItemList.subList(0, partSize).clear();
							}
						}
						if(searchItemList.size()>0){
							dvReportSearchTmpMapper.insertDvReportSearchTmpByBatch(apreVo.getUserid(), searchItemList);
						}
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
					apreVo.setSearchValue(searchItemList.size()>0?searchItemList.toArray(new String[searchItemList.size()]):null);
				}else{
					apreVo.setSearchValue(null);
				}
			}else if("activeName".equals(apreVo.getSearchName())){
				if(apreVo.getSearchValue().length>0){
					if(StringUtils.isNotBlank(apreVo.getSearchValue()[0])){
						apreVo.setSearchValue(apreVo.getSearchValue());
					}
				}else{
					apreVo.setSearchValue(null);
				}
			}
			BeanUtils.copyProperties(apreVo, aprePo);
			//用户ID，UUID组成下载ID
			String downloadId = aprePo.getUserid()+UUID.randomUUID().toString().replaceAll("-", "");
			String downloadReportName = apreVo.getReportName();
			String fileName =downloadId+downloadReportName+".xlsx";
			
			DvReportDownloadStatusEntity dvReportDownloadStatusEntity = new DvReportDownloadStatusEntity();
			dvReportDownloadStatusEntity.setDownloadId(downloadId);
			dvReportDownloadStatusEntity.setFileName(fileName);
			dvReportDownloadStatusEntity.setReportName(downloadReportName);
			dvReportDownloadStatusEntity.setReportType(reporttype);
			dvReportDownloadStatusEntity.setUserid(apreVo.getUserid());
			dvReportDownloadStatusEntity.setUsername(apreVo.getUsername());
			dvReportDownloadStatusEntity.setUserrealname(apreVo.getUserrealname());
			dvReportDownloadStatusEntity.setTargetName(JSON.toJSONString(reportCommonService.getTargetNameList(targetArr, reporttype)));
			dvReportDownloadStatusEntity.setIp(DvUtils.getIp(request));
			int rownum = activePackageReportExportMapper.queryCount(aprePo);
			if(reportDownloadStatusMapper.insertReport(dvReportDownloadStatusEntity)>0){
				DownloadTask downloadTask = new DownloadTask(fileName,targetList,rownum, aprePo, dvReportDownloadStatusEntity);
				new Thread(downloadTask).start();  
				return ServerResponse.createBySuccessMessage("加入下载列表成功！");
			}else{
				return ServerResponse.createByErrorMessage("加入下载列表失败！");
			}
	}
		
		class DownloadTask implements Runnable{
			public  boolean flag = true;
			private String fileName;
			private Integer rownum;
			private List<String> targetList;
			private ActivePackageReportExportPO aprePo;
			private DvReportDownloadStatusEntity dvReportDownloadStatusEntity;
			public DownloadTask(String fileName,List<String> targetList,int rownum,ActivePackageReportExportPO aprePo,DvReportDownloadStatusEntity dvReportDownloadStatusEntity){
				this.fileName = fileName;
				this.rownum = rownum;
				this.aprePo = aprePo;
				this.targetList = targetList;
				this.dvReportDownloadStatusEntity = dvReportDownloadStatusEntity;
			}
			public void stopThread(){
				flag = false;
			}
			@Override
			public void run() {
				while (flag){
					OutputStream ops = null;
					ExcelExportResult exportResult = null;
					try {
						ops = new FileOutputStream(downloadPath+fileName);
						exportResult = context.createEmptyExcelForPart(reporttype,DwActivePackageEntity.class,targetList);
						int pageSize = 40000;
						int totalPage = (int)Math.ceil(rownum/pageSize);
						totalPage += rownum%pageSize>0?1:0; 
						for(int i=1;i<=totalPage;i++){
							exportResult.append(activePackageReportExportMapper.queryData(aprePo, i, pageSize));
						}
					Workbook workbook = exportResult.build();
					workbook.write(ops);
					ops.close();
					workbook.close();
					dvReportDownloadStatusEntity.setEndDate(new Date());
					dvReportDownloadStatusEntity.setTimeConsume(Math.round(dvReportDownloadStatusEntity.getEndDate().getTime()-dvReportDownloadStatusEntity.getBeginDate().getTime())/1000);
					dvReportDownloadStatusEntity.setDownloadFlag(1);
					reportDownloadStatusMapper.updateReportById(dvReportDownloadStatusEntity);
					
					this.stopThread();
					} catch (Exception e) {
						System.out.println("ActivePackageReprot awaitTermination interrupted: " + e);  
						this.stopThread();
					}
				}
			}
		}
	private String getTrueOrFalseCheackBoxValue(String[] cheackBoxValue){
		return cheackBoxValue.length>1?"全选":cheackBoxValue[0];
	}
	public Object addOrUpdateReport(ActivePackageReportExportVO apreVo){
		String reportid = apreVo.getReportid();
		String[] targetArr = apreVo.getTarget();
		
		List<String> targetNameList = reportCommonService.getTargetNameList(targetArr, reporttype);
		
		AcitvePackageReportManageVO acitvePackageReportManageVO = new AcitvePackageReportManageVO();
		BeanUtils.copyProperties(apreVo, acitvePackageReportManageVO);
		acitvePackageReportManageVO.setTargetName(targetNameList);
		acitvePackageReportManageVO.setSaveTime(DvDateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
		acitvePackageReportManageVO.setIsWhole(getTrueOrFalseCheackBoxValue(apreVo.getIsWhole()));
		acitvePackageReportManageVO.setIsStopUse(getTrueOrFalseCheackBoxValue(apreVo.getIsStopUse()));
		acitvePackageReportManageVO.setIsVerify(getTrueOrFalseCheackBoxValue(apreVo.getIsVerify()));
		acitvePackageReportManageVO.setIsTempletShow(getTrueOrFalseCheackBoxValue(apreVo.getIsTempletShow()));
		acitvePackageReportManageVO.setIsLabelShow(getTrueOrFalseCheackBoxValue(apreVo.getIsLabelShow()));
		//权限修改了平台ID,对应的平台名称也要变
		acitvePackageReportManageVO.setSourcename(reportCommonService.getOrderSourceName(apreVo.getOrdersource(), commonService.getOrderSource(1, apreVo.getUserid(),reporttype)));
		//添加附件名字
		if(StringUtils.isNotBlank(apreVo.getUploadFileId())){
			String uploadFileName = reportImportStatusMapper.queryReportStatusByUUID(apreVo.getUploadFileId()).getReportName();
			apreVo.setUploadFileName(uploadFileName);
			acitvePackageReportManageVO.setUploadFileName(apreVo.getUploadFileName());
		}
		if("activeName".equals(apreVo.getSearchName())){
			String[] searchArr = apreVo.getSearchValue();
			if(searchArr!=null&&searchArr.length>0){
				acitvePackageReportManageVO.setSearchValue(apreVo.getSearchValue()[0]);
			}
		}
		if(StringUtils.isNotBlank(reportid)){
			DvReportExportStatus dvReportExportStatus = new DvReportExportStatus();
			dvReportExportStatus.setReportid(reportid);
			dvReportExportStatus.setReportName(apreVo.getReportName());
			dvReportExportStatus.setReportparam(JSON.toJSONString(apreVo));
			dvReportExportStatus.setReportManageParam(JSON.toJSONString(acitvePackageReportManageVO));
			if(reportExportStatusMapper.updateReportStatus(dvReportExportStatus)>0){
				return ServerResponse.createBySuccessMessage("修改报表成功!");
			}else{
				return ServerResponse.createBySuccessMessage("修改报表失败!");
			}
		}else{
			//加入报表前需要根据用户ID，报表名去判断是否有重名的报表
			if(reportExportStatusMapper.queryReport(apreVo.getUserid(), apreVo.getReportName())>0){
				return ServerResponse.createByErrorMessage("已存在相同名称的报表，请重新命名!");
			}else{
				reportid = reporttype+String.valueOf(System.currentTimeMillis())+String.valueOf((int)((Math.random()*9+1)*100000));
				apreVo.setReportid(reportid);
				acitvePackageReportManageVO.setReportid(reportid);
				DvReportExportStatus dvReportExportStatus = new DvReportExportStatus();
				BeanUtils.copyProperties(apreVo, dvReportExportStatus);
				dvReportExportStatus.setCreatetime(new Date());
				dvReportExportStatus.setReportparam(JSON.toJSONString(apreVo));
				dvReportExportStatus.setReportManageParam(JSON.toJSONString(acitvePackageReportManageVO));
				dvReportExportStatus.setReporttype(reporttype);
				dvReportExportStatus.setFileName(apreVo.getUploadFileId()+apreVo.getUploadFileName());
				if(reportExportStatusMapper.insertReportStatus(dvReportExportStatus)>0){
					return ServerResponse.createBySuccessMessage("添加报表成功!");
				}else{
					return ServerResponse.createByErrorMessage("添加报表失败!");
				}
			}
		}
	}
	
	private void addCategory(ActivePackageReportExportPO aprePo,String categoryId){
		if("productInfo".equals(categoryId)){
			aprePo.setProductInfo(true);
		}else if("activeSales".equals(categoryId)){
			aprePo.setActiveSales(true);
		}
	}
	private void handleTargetSql(ActivePackageReportExportPO aprePo,List<String> targetList){
		for(String target : targetList){
			if(target.equals("dataDate")){
				aprePo.setDataDateSql(true);
			}else if(target.equals("singleqty")){
				aprePo.setSingleqtySql(true);
			}else if(target.equals("warenameGift")){
				aprePo.setWarenameGiftSql(true);
			}else if(target.equals("warecodeGift")){
				aprePo.setWarecodeGiftSql(true);
			}else if(target.equals("marketingcosts")){
				aprePo.setMarketingcostsSql(true);
			}else if(target.equals("kitvalue")){
				aprePo.setKitvalueSql(true);
			}else if(target.equals("specialprice")){
				aprePo.setSpecialpriceSql(true);
			}else if(target.equals("price")){
				aprePo.setPriceSql(true);
			}else if(target.equals("isdetailshow")){
				aprePo.setIsdetailshowSql(true);
			}else if(target.equals("iskeyware")){
				aprePo.setIskeywareSql(true);
			}else if(target.equals("department")){
				aprePo.setDepartmentSql(true);
			}else if(target.equals("warename")){
				aprePo.setWarenameSql(true);
			}else if(target.equals("warecode")){
				aprePo.setWarecodeSql(true);
			}else if(target.equals("disamt")){
				aprePo.setDisamtSql(true);
			}else if(target.equals("fullamount")){
				aprePo.setFullamountSql(true);
			}else if(target.equals("starttime")){
				aprePo.setStarttimeSql(true);
			}else if(target.equals("endtime")){
				aprePo.setEndtimeSql(true);
			}else if(target.equals("prmdesc")){
				aprePo.setPrmdescSql(true);
			}else if(target.equals("prmtypename")){
				aprePo.setPrmtypenameSql(true);
			}else if(target.equals("prmflagname")){
				aprePo.setPrmflagnameSql(true);
			}else if(target.equals("kitsubtitle")){
				aprePo.setKitsubtitleSql(true);
			}else if(target.equals("kitprice")){
				aprePo.setKitpriceSql(true);
			}else if(target.equals("kitremark")){
				aprePo.setKitremarkSql(true);
			}else if(target.equals("cusgradename")){
				aprePo.setCusgradenameSql(true);
			}else if(target.equals("iswhole")){
				aprePo.setIswholeSql(true);
			}else if(target.equals("isstop")){
				aprePo.setIsstopSql(true);
			}else if(target.equals("ischeck")){
				aprePo.setIscheckSql(true);
			}else if(target.equals("istemplateshow")){
				aprePo.setIstemplateshowSql(true);
			}else if(target.equals("istagshow")){
				aprePo.setIstagshowSql(true);
			}else if(target.equals("fullqty")){
				aprePo.setFullqtySql(true);
			}else if(target.equals("sourcename")){
				aprePo.setPlatformSql(true);
			}else if(target.equals("ordersource")){
				aprePo.setOrdersourceSql(true);
			}
		}

	}
	private List<String> getTargetList(String[] targetArr){
		List<String> targetList = Lists.newArrayList();
		String[] defaultArr = new String[]{"prmcode","prmname"};
		for(String defaultItem : defaultArr){
			targetList.add(defaultItem);
		}
		for(String targetItem : targetArr){
			targetList.add(targetItem);
		}
		return targetList;
	}
}
